#!/usr/bin/env python
# -*- coding: latin-1 -*-

import sys
import os
import xmpp
from xmpp.protocol import *
from rss import * 
from config import config



def presenceHandler(conn, pres_node):
    """Presence handler"""
    pass


def subscriptionsHandler(conn, pres_node):
    """Subscription handler"""
    tipo = pres_node.getType()
    if tipo == "subscribe":
        p = Presence(to=pres_node.getFrom(),typ='subscribe')
        conn.send(p)
        p = Presence(to=pres_node.getFrom(),typ='subscribed')
        conn.send(p)
    elif tipo == "unsubscribe":
        p = Presence(to=pres_node.getFrom(),typ='unsubscribe')
        conn.send(p)
        p = Presence(to=pres_node.getFrom(),typ='unsubscribed')
        conn.send(p)
        

def iqVersion(conn, iq_node):
    """IQ Version request"""
    i = Iq(
        typ='result', 
        queryNS='jabber:iq:version', 
        to=iq_node.getFrom(),
        attrs={'id': iq_node.getID()}, 
        payload=[
            Node('name', payload=['xmpppy']),
            Node('os', payload=[os.name.upper()])
        ]
    )
    conn.send(i)
    raise NodeProcessed



class Bot(object):
  rss = Rss()
  reader = Reader()
  jid = xmpp.JID(config['jid'])
  password = config['password']
  waitcount = 40 
  def run_and_listen(self):
    self.waitcount = config['waitcount']
    self.count = self.waitcount
    self._connect()
    self._bindingHandlers()
    self._run()

  def _connect(self):
    self.client = xmpp.Client(self.jid.getDomain())
    self.client.connect( 
      (
        config['server'],
        config['port'],
      )
    )
    self.client.auth(self.jid.getNode(), self.password, 'booty')
    self.client.sendInitPresence(requestRoster=1)

  def _bindingHandlers(self):
    self.client.RegisterHandler('iq', iqVersion, typ='get', ns='jabber:iq:version')
    self.client.RegisterHandler('message', self.messageHandler)
    self.client.RegisterHandler('presence', presenceHandler, typ=None)
    self.client.RegisterHandler('presence', presenceHandler, typ="unavailable")
    self.client.RegisterHandler('presence', subscriptionsHandler, typ="subscribe")
    self.client.RegisterHandler('presence', subscriptionsHandler, typ="subscribed")
    self.client.RegisterHandler('presence', subscriptionsHandler, typ="unsubscribe")
    self.client.RegisterHandler('presence', subscriptionsHandler, typ="unsubscribed")

  def messageHandler(self, conn, mess_node):
    user = str(mess_node.getFrom()).split("/")[0]
    body = mess_node.getBody()
    
    if body.startswith("add http") and '\n' not in body:
      reply = "\n*Agregando Feed*"
      feed = body[4:].strip()
      ok = self.rss.addurl(user, feed)  
      if not ok:
        reply += "\nFeed %s ya esta agregado para %s\n" % (feed, user)
      else:
        reply += "\nURL: %s\nJID: %s\n\n Dentro de poco empezarás a recibir las noticias." %(feed, jid)
        self.client.send(xmpp.Message(user, reply, typ='chat'))
    elif body.startswith("list"):
      reply = "\n*Lista de Feeds* \n"
      rsss = self.rss.listfeeds(user)
      for x in rsss:
        reply += "%d - %s\n" % (rsss.index(x), x) 
      self.client.send(xmpp.Message(user, reply, typ='chat'))
    elif body.startswith("del"):
      id = int(body[4:].strip())
      reply = "\n*Feed eliminado*\n"
      self.rss.remove(user, id)
      self.client.send(xmpp.Message(user, reply, typ='chat'))
    elif body.startswith("help"):
      reply = "\nGood news! your help it's here:\nsend me commands:\n  - help: this command ... ;)\n  - add <url>: add the <url> to database.\n  - list: list the urls to read with indexes\n  - del <index>: remove the url with <index>\n\ni'm waiting ... \n" 
      self.client.send(xmpp.Message(user, reply, typ='chat'))
    else:
      self.client.send(xmpp.Message(user, "comando no reconocido", typ='chat'))
  

  def countdown(self):
    result = False
    if self.count > 0:
      self.count = self.waitcount
      result = True
    else:
      self.count = self.countdown -1
      result = False
    return result



  def _run(self):
    try:
      while self.client.Process(1) and self.countdown():
        result = self.reader.read()
        for jid, rss in result.iteritems():
          if rss:
            reply = "\n"
            for item in rss:
              reply += "*%s*\n" % item['title']
              reply += "%s ...\n" % item['summary_detail']['value'][:200]
              reply += "%s\n\n" % item['link']
            self.client.send(xmpp.Message(jid, reply, typ='chat'))

    except KeyboardInterrupt:
      self.reader.stop()
      sys.exit(1)

 
if __name__ == '__main__':
  bot = Bot()
  bot.run_and_listen()
